<?php
/**
 * Plugin for ACL quering on user request
 * 
 * @uses       Zend_Controller_Plugin_Abstract
 * @package    FireFeed
 * @subpackage Plugin
 */
class FireFeed_Plugin_Acl extends Zend_Controller_Plugin_Abstract 
{
	/**
	 * @var Zend_Acl
	 */
	private $_acl = null;
	
	/**
	 * @var Zend_Auth
	 */
	private $_auth = null;

	function __construct(Zend_Acl $acl, Zend_Auth $auth) 
	{
	   $this->_acl = $acl;
	   $this->_auth = $auth;
	}
	
	/**
     * Called before an action is dispatched by Zend_Controller_Dispatcher.
     * So, there we can query the ACL against the user request.
	 */
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
	    if ($this->_auth->hasIdentity()) {
            $role = $this->_auth->getStorage()->read()->roles->name;
        } else {
            $role = FireFeed_Acl_Roles::GUEST;
        }
        
		$resource = $request->getControllerName();
		$privilege = $request->getActionName();
		if ($resource != "error") { // Skip requests for error controller
		  if (!$this->_acl->isAllowed($role, $resource, $privilege)) {
		  	
			$request->setControllerName('error')
		            ->setActionName('notallowed');
		  }
		}
	}
}
